#pragma once
#include<iostream>
using namespace std;
template<class K>
struct BSTreeNode
{
	BSTreeNode<K>* _left;
	BSTreeNode<K>* _right;
	K _key;
	BSTreeNode(const K& key)
		:_left(nullptr)
		, _right(nullptr)
		, _key(key)
	{}


};
template<class K>
class BSTree
{
	typedef BSTreeNode<K> Node;
public:
	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;



		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;


			}
			else
			{

				return false;


			}
		}
			cur = new Node(key);
			if (parent->_key < key)
			{
				parent->_right = cur;



			}
			else
			{
				parent->_left = cur;


			}

			return true;




}

		void inorder()
	{
		_inorder(_root);


	}
		bool find(const K& key)
		{
			Node* cur = _root;
			while (cur)
			{
				if (cur->_key < key)
				{
					cur = cur->_right;


				}
				else if(cur->_key>key)
				{
					cur = cur->_left;
				}
				else
				{
					return true;
				}



			}
			return false;
		
		
		
		
		}


		bool earse(const K& key)
		{
			Node* parent = nullptr;
			Node* cur = _root;
			while (cur)
			{
				if (cur->_key < key)
				{
					parent = cur;
					cur = cur->_right;


				}
				else if (cur->_key > key)
				{

					parent = cur;
					cur = cur->_left;

				}
				else
				{
					if (cur->_left == nullptr)
					{
						if (parent->_left == cur)
						{

	                       parent->_left = cur->_right;
						}
						else
						{
							parent->_right= cur->_left;


						}
						delete cur;




					}
					else if(cur->_right == nullptr)
					{
						if (parent->_left == cur)
						{

							parent->_left = cur->_right;
						}
						else
						{
							parent->_right = cur->_left;


						}

						delete cur;

					}
					else
					{
						Node* parent = cur;
						Node* subleft = cur->_left;
						while (subleft->_left)
						{
							parent = subleft;
							subleft = subleft->_left;
						}

						cur->_key = subleft->_key;
						if (subleft == parent->_left)
						{
							parent->_left = subleft->_right;
						}
						else
						{
							parent->_right = subleft->_right;
						}
						delete  subleft;
					}

					   return  true;
				
				
				}




			}
			return false;
		}

private:

	void _inorder(Node* root)
	{
		if (root == nullptr)
			return;
		_inorder(root->_left);
		cout << root->_key << " ";
		_inorder(root->_right);
	
	}

private:
	Node* _root = nullptr;

};
void test()
{
	BSTree<int>st;
	int a[] = {8,3,1,10,6,4,7,14,13};
	for (auto e : a)
	{
		st.Insert(e);
	}
	st.inorder();
	cout << endl;
	st.earse(10);
	st.inorder();




}

